// 游戏页交互逻辑
document.addEventListener('DOMContentLoaded', function() {
    // 初始化游戏状态
    let gameState = {
        coins: 5000,
        score: 0,
        time: 100,
        mode: 'build', // 'build' 或 'operation'
        selectedTool: null,
        buildings: [],
        roads: [],
        citizens: [],
        navigators: []
    };

    // 获取DOM元素
    const coinsDisplay = document.getElementById('coins');
    const scoreDisplay = document.getElementById('score');
    const timeDisplay = document.getElementById('time');
    const playerNameDisplay = document.getElementById('player-name');
    const gameMap = document.getElementById('game-map');
    
    // 设置玩家昵称
    const playerName = localStorage.getItem('playerName');
    if (playerName) {
        playerNameDisplay.textContent = playerName;
    }

    // 工具按钮事件
    document.getElementById('road-paver').addEventListener('click', function() {
        gameState.selectedTool = 'road-paver';
    });

    document.getElementById('navigator').addEventListener('click', function() {
        gameState.selectedTool = 'navigator';
    });

    document.getElementById('remove-tool').addEventListener('click', function() {
        gameState.selectedTool = 'remove';
    });

    document.getElementById('citizen').addEventListener('click', function() {
        gameState.selectedTool = 'citizen';
    });

    // 返回主页按钮
    document.getElementById('back-to-main').addEventListener('click', function() {
        window.location.href = 'index.html';
    });

    // 设置按钮
    document.getElementById('settings').addEventListener('click', function() {
        document.getElementById('settings-modal').style.display = 'block';
    });

    // 保存游戏
    document.getElementById('save-game').addEventListener('click', function() {
        saveGameState();
    });

    // 加载游戏
    document.getElementById('load-game').addEventListener('click', function() {
        loadGameState();
    });

    // 建造模式切换
    document.getElementById('build-mode').addEventListener('click', function() {
        toggleBuildMode();
    });

    // 初始化游戏地图
    function initGameMap() {
        // 创建20x10的网格地图
        gameMap.style.gridTemplateColumns = 'repeat(20, 1fr)';
        gameMap.style.gridTemplateRows = 'repeat(10, 1fr)';
        
        for (let i = 0; i < 200; i++) {
            const cell = document.createElement('div');
            cell.className = 'map-cell';
            cell.dataset.index = i;
            cell.addEventListener('click', handleCellClick);
            gameMap.appendChild(cell);
        }
        
        // 随机生成建筑
        generateBuildings();
    }

    // 处理单元格点击
    function handleCellClick(event) {
        const cell = event.target;
        const index = parseInt(cell.dataset.index);
        
        switch (gameState.selectedTool) {
            case 'road-paver':
                placeRoad(cell, index);
                break;
            case 'navigator':
                placeNavigator(cell, index);
                break;
            case 'remove':
                removeItem(cell, index);
                break;
        }
    }

    // 放置道路
    function placeRoad(cell, index) {
        if (gameState.coins >= 50) {
            cell.classList.add('road');
            gameState.roads.push(index);
            gameState.coins -= 50;
            updateUI();
        }
    }

    // 放置导航工具
    function placeNavigator(cell, index) {
        if (gameState.coins >= 500) {
            cell.classList.add('navigator');
            gameState.navigators.push(index);
            gameState.coins -= 500;
            updateUI();
        }
    }

    // 移除物品
    function removeItem(cell, index) {
        if (cell.classList.contains('road')) {
            cell.classList.remove('road');
            gameState.roads = gameState.roads.filter(i => i !== index);
            gameState.coins += 50;
        } else if (cell.classList.contains('navigator')) {
            cell.classList.remove('navigator');
            gameState.navigators = gameState.navigators.filter(i => i !== index);
            gameState.coins += 500;
        }
        updateUI();
    }

    // 切换建造模式
    function toggleBuildMode() {
        if (gameState.mode === 'build') {
            gameState.mode = 'operation';
            startOperationMode();
        } else {
            gameState.mode = 'build';
            stopOperationMode();
        }
    }

    // 开始操作模式
    function startOperationMode() {
        // 生成市民
        generateCitizens();
        
        // 启动计时器
        const timer = setInterval(() => {
            if (gameState.time > 0) {
                gameState.time--;
                updateUI();
                
                // 移动市民
                moveCitizens();
                
                // 检查游戏状态
                checkGameStatus();
            } else {
                clearInterval(timer);
                gameOver(false);
            }
        }, 1000);
    }

    // 停止操作模式
    function stopOperationMode() {
        // 重置分数和时间
        gameState.score = 0;
        gameState.time = 100;
        updateUI();
        
        // 清除市民
        gameState.citizens = [];
        document.querySelectorAll('.citizen').forEach(c => c.remove());
    }

    // 更新UI显示
    function updateUI() {
        coinsDisplay.textContent = gameState.coins;
        scoreDisplay.textContent = gameState.score;
        timeDisplay.textContent = gameState.time;
    }

    // 初始化游戏
    initGameMap();
    updateUI();
});